import { getData } from '@vimi/utils-api'
import { SERVICE_NAME } from '@/gov/plugins/constant'

const state = {
  myTaskCount: {},
}

const getters = {
  myTaskCount: state => state.myTaskCount,
}

const actions = {
  async getMyTaskCount({ commit, rootGetters }, force = true) {
    if (!force && state.myTaskCount.noArchive) {
      return Promise.resolve(state.myTaskCount)
    }
    const res = await getData(
      SERVICE_NAME,
      'task_list_count_view',
      {
        address_code: rootGetters.user.queryAddressCode,
        'orWhere.task_person.in': `all-db,${rootGetters.clientId}`,
        'orWhere.task_person.like': rootGetters.userId,
        groupFields: ['task_type', 'task_status'],
        fields: ['task_type', 'task_status'],
        groupFunc: 'count(task_list_count_view.task_type)',
      },
      {
        N1task_type: 'ASC',
      }
    )
    const resData = (res && res.data) || []
    let data = {}
    resData.forEach(item => {
      if (data[item.task_type]) {
        if (+item.task_status === 1) {
          data[item.task_type].process = item.p || 0
        } else {
          data[item.task_type].num = item.p || 0
        }
      } else {
        data[item.task_type] = {
          num: +item.task_status === 1 ? 0 : item.p,
          process: +item.task_status === 1 ? item.p : 0,
        }
      }
    })
    commit('myTaskCount', data)
    return data
  },
}

const mutations = {
  myTaskCount: (state, payload) => (state.myTaskCount = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
